package pl.uz.zgora.plan;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

public class SalaDataSource {
	private SQLiteDatabase database;
	
	public SalaDataSource(SQLiteDatabase database)
	{
		this.database = database;
	}
	
	public boolean addSala(final Sala sala)
	{
		if(!database.isOpen())
			throw new SQLiteException("Database not open!");
		
		if(database.isReadOnly())
			throw new SQLiteException("Wrong database connection!");
		
		ContentValues values = new ContentValues();
		values.put(PlanDatabaseHandler.KEY_SALA, sala.getIdSali());
		values.put(PlanDatabaseHandler.KEY_BUILDING, sala.getSymbolBudynku());
		values.put(PlanDatabaseHandler.KEY_NAME, sala.getNazwa());
		
		if(database.insert(PlanDatabaseHandler.TABLE_SALA, null, values) == -1)
			return false;
		
		return true;
	}
	
	public boolean addSalaList(final ArrayList<Sala> sale)
	{
		if(sale == null || sale.size() == 0) {
			return false;
		}
		
		for(Sala sala: sale) {
			if(!addSala(sala)) {
				return false;
			}
		}
		
		return true;
	}
	
	public ArrayList<Sala> getSale()
	{
		if(!database.isOpen())
			throw new SQLiteException("Database not open!");
		
		ArrayList<Sala> sale = new ArrayList<Sala>();
		Cursor cursor = null;
			
		cursor = database.query(PlanDatabaseHandler.TABLE_SALA,
					null, null, null, null, null, null);
	
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			final Sala sala = SalaDataSource.cursorToSala(cursor);
			sale.add(sala);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();

		return sale;
	}
	
	public Sala getSala(final Integer idSali)
	{
		if(!database.isOpen())
			throw new SQLiteException("Database not open!");
		
		Cursor cursor = null;
		
		if(idSali > 0)
			cursor = database.query(PlanDatabaseHandler.TABLE_SALA,
				null, "idSali = " + idSali.toString(), null, null, null, null);
		
		cursor.moveToFirst();
		final Sala sala = SalaDataSource.cursorToSala(cursor);
		// Make sure to close the cursor
		cursor.close();

		return sala;
	}
	
	public static Sala cursorToSala(Cursor cursor)
	{
		Sala sala = new Sala();
		sala.setIdSali(cursor.getInt(0));
		sala.setSymbolBudynku(cursor.getString(1));
		sala.setNazwa(cursor.getString(2));
		return sala;
	}
}
